# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
import hashlib
import json
import time
import urllib

from scrapy import signals
from urllib import request

from scrapy.exceptions import IgnoreRequest

from Netease.gl import gl_proxy, gl_proxy_get_api, gl_proxy_del_api
from Netease.util.utils import utils


class ProxyMiddleware(object):
    def process_request(self,request,spider):

        res = urllib.request.urlopen('http://www.xiongmaodaili.com/xiongmao-web/api/glip?secret=84796a57e936392a37ae94c38979aacd&orderNo=GL20180709095907RNTV3jt9&count=1&isTxt=1').read().decode("utf-8")
        request.meta['proxy'] = 'http://' + res

        # res=urllib.request.urlopen(gl_proxy_get_api).read().decode("utf-8")
        # request.meta['proxy'] = 'http://'+res
        # print("using proxy:", res)
        # pass
        # 个人中心获取orderno与secret
        # orderno = "DT20180709120833TzE0UtnH"
        # secret = "84796a57e936392a37ae94c38979aacd"
        # ip = "dynamic.xiongmaodaili.com"
        # port = "8088"
        # ip_port = ip + ":" + port
        # timestamp = str(int(time.time()))  # 计算时间戳
        # txt = "orderno=" + orderno + "," + "secret=" + secret + "," + "timestamp=" + timestamp
        # txt = txt.encode()
        # md5_string = hashlib.md5(txt).hexdigest()  # 计算sign
        # sign = md5_string.upper()  # 转换成大写
        # auth = "sign=" + sign + "&" + "orderno=" + orderno + "&" + "timestamp=" + timestamp
        # proxy = {"http": "http://" + ip_port, "https": "https://" + ip_port}
        # request.headers['Authorization'] = auth
        # request.meta['proxies'] = proxy
        pass

    def process_response(self,request,response,spider):

        # result = json.loads(response.text)
        #
        # if result.get("code") != 200:
        #     # 更换代理
        #     res = json.load(urllib.request.urlopen(
        #         "http://www.xiongmaodaili.com/xiongmao-web/api/glip?secret=84796a57e936392a37ae94c38979aacd&orderNo=GL20180701140510Ve2oCays&count=1&isTxt=0"))
        #     if (res.get("code") == '0'):
        #         obj = res.get("obj")
        #         proxy = 'http://' + obj[0].get("ip") + ":" + obj[0].get("port")
        #         print("error code:",result.get("code"),"change proxy to ", proxy)
        #         request.meta['proxy'] = proxy
        #     else:
        #         print("网易返回 ",result.get("code")," 获取代理ip失败 code:", res.get("code"), "msg:", res.get("msg"))
        #         # 延时几秒
        #         time.sleep(5)
        #     # 更换代理后重新发起这个request
        #     return request

        # 返回值不为json 说明这个用户没粉丝
        if utils.is_json(response.text)==False:
            return response

        result = json.loads(response.text)

        if result.get("code") == -460:
            old_proxy=request.meta['proxy']
            urllib.request.urlopen(gl_proxy_del_api.format(proxy=old_proxy[7:]))
            print("-460 cheating 删除代理:",old_proxy)
            res = urllib.request.urlopen(gl_proxy_get_api).read().decode("utf-8")
            request.meta['proxy'] = 'http://' + res
            return request
        return response

    # def process_exception(self,request,exception,spider):

    #     old_proxy = request.meta['proxy']
    #     urllib.request.urlopen(gl_proxy_del_api.format(proxy=old_proxy[7:]))
    #     print("删除代理:", old_proxy)
    #     res = urllib.request.urlopen(gl_proxy_get_api).read().decode("utf-8")
    #     request.meta['proxy'] = 'http://' + res
    #     return request

class NeteaseSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Response, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class NeteaseDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)
